<?php
namespace app\interfaces\controller;

use app\interfaces\model\MemberDistributionRecords;
use think\Db;
use think\Cache;
use think\Request;
use think\Exception;
use app\interfaces\model\Shop as ShopModel;
use app\interfaces\model\Member as MemberModel;
use app\interfaces\model\MemberOrder as MemberOrderModel;
use app\interfaces\model\MemberRefund as MemberRefundModel;
use app\interfaces\model\MemberCoupon as MemberCouponModel;
use app\interfaces\model\MemberPacket as MemberPacketModel;
use app\interfaces\model\MemberAddress as MemberAddressModel;
use app\interfaces\model\FreightTemplate as FreightTemplateModel;
use app\interfaces\model\MemberOrderAttached as MemberOrderAttachedModel;
use think\Log;
use think\Session;
use think\Cookie;

class MemberOrder
{

    /*
     * 用户端 - 确认订单
     * @param  string $user_id  会员ID
     */
    public function order_affirm33()
    {

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $goods_id = Request::instance()->param('goods_id', '');
        $cart_id = Request::instance()->param('cart_id', '');
        $address_id = Request::instance()->param('address_id');

        if (empty($user_id)) throw new Exception('not Empty');

        // 搜索条件
        $condition['member_shopping_cart.member_id'] = ['eq', $user_id];
        $condition['member_shopping_cart.id'] = ['in', $cart_id];

        if (!empty($goods_id)) $condition['goods_id'] = ['in', $goods_id];


        if ($address_id) {
            $address = (new MemberAddressModel())->where(['id' => $address_id])
                ->field('id,name,phone,address,area_info,template_id')->find();
        } else {
            $address = MemberAddressModel::where(['member_id' => $user_id])
                ->field('id,name,phone,address,area_info,template_id')
                ->order(['status' => 'asc', 'create_time' => 'desc'])
                ->find();
        }


        // 查询商品ID
        $result = Db::view('member_shopping_cart', 'id as cart_id,member_id,goods_id,attr,number,price,limited_status')
            ->view('shop_goods', 'id,member_id,title,thumb_img,rebate_percentage,freight,charges', 'shop_goods.id = member_shopping_cart.goods_id')
            ->view('shop', 'member_id,title as shop_title', 'shop_goods.member_id = shop.member_id')
            ->where($condition)
            ->select()->toArray();

        if ($result) {
            if ($address) {
                foreach ($result as &$value) {
                    $ini['member_id'] = $value['member_id'];
                    $ini['area_id'] = ['like', '%,' . $address['template_id'] . ',%'];
                    $freight = (new FreightTemplateModel())->where($ini)->value('price');
                    if ($freight) {
                        $value['freight'] = $freight;
                    } else {
                        $value['freight'] = 0;
                    }

                }
            } else {
                foreach ($result as &$value) {
                    $value['freight'] = 0;
                }
                $address = ['id' => '', 'name' => '', 'phone' => '', 'address' => '', 'area_info' => '', 'template_id' => ''];
            }

        }


        // $freight = (new FreightTemplateModel())->where($ini)->value('price');

        // halt($this->cartGrouping($result, 'shop_title', 'title', 'list', 'member_id', 'shop_id'));
        // 积分是否抵扣
        // $integral = MemberModel::where(['id' => $user_id])->field('integral')->find();
        // $integral['points_deduction'] = Cache::get('web_points_deduction');
        // $integral['deduction_percentage'] = $integral['integral'] / Cache::get('web_deduction_percentage');

        $balance = MemberModel::where(['id' => $user_id])->value('balance');

        return [
            'code'    => 200,
            'message' => '成功',
            'address' => $address,
            'balance' => $balance,
            'data'    => $this->cartGrouping($result, 'shop_title', 'title', 'list', 'member_id', 'shop_id', 'freight', 'shop_freight')
        ];
    }

    public function order_affirm()
    {

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $goods_id = Request::instance()->param('goods_id', '');
        $cart_id = Request::instance()->param('cart_id', '');
        $address_id = Request::instance()->param('address_id');
        if (empty($user_id)) throw new Exception('not Empty');

        // 搜索条件
        $condition['member_shopping_cart.member_id'] = ['eq', $user_id];
        $condition['member_shopping_cart.id'] = ['in', $cart_id];

        if (!empty($goods_id)) $condition['goods_id'] = ['in', $goods_id];


        if ($address_id) {
            $address = (new MemberAddressModel())->where(['id' => $address_id])
                ->field('id,name,phone,address,area_info,template_id')->find();
        } else {
            $address = MemberAddressModel::where(['member_id' => $user_id])
                ->field('id,name,phone,address,area_info,template_id')
                ->order(['status' => 'asc', 'create_time' => 'desc'])
                ->find();
            if(is_null($address)){
                $address['id'] = '';
                $address['name'] = '';
                $address['phone'] = '';
                $address['address'] = '';
                $address['area_info'] = '';
                $address['template_id'] = '0';

            }

        }


        // 查询商品ID
        $result = Db::view('member_shopping_cart', 'id as cart_id,member_id,goods_id,attr,number,price')
            ->view('shop_goods', 'id,member_id,title,thumb_img,freight', 'shop_goods.id = member_shopping_cart.goods_id')
            ->where($condition)
            ->select()->toArray();
        $ret['goods_total_price'] = 0;
        $ret['freight_total_price'] = 0;
        foreach ($result as $k => $v){
            $ret['goods_total_price'] = bcadd(bcmul($v['price'],$v['number'],2),$ret['goods_total_price'],2);
            $ret['freight_total_price'] = bcadd(bcmul($v['freight'],$v['number'],2),$ret['freight_total_price'],2);
        }
        $ret['list'] = $result;
        if(empty($cart_id)){
            $price = Request::instance()->param('price');
            $number = Request::instance()->param('number');
            $attr = Request::instance()->param('attr');
            if (!empty($attr)) {
                // 减少属性表库存
                $price = Db::name('shop_spec_attr')->where(['attribute' => $attr, 'goods_id' => $goods_id])->value('price');
            }else{
                $price = Db::name('shop_goods')->where(['id' => $goods_id])->value('price');
            }
            $find = Db::name('shop_goods')->where('id',$goods_id)->find();
            $ret['goods_total_price'] = bcmul($price,$number,2);
            $ret['freight_total_price'] = bcmul($find['freight'],$number,2);
            $arr['member_id'] = $user_id;
            $arr['price'] = $price;
            $arr['number'] = $number;
            $arr['freight'] = $find['freight'];
            $arr['member_id'] = $user_id;
            $arr['title'] = $find['title'];
            $arr['thumb_img'] = $find['thumb_img'];
            $arr['id'] = $goods_id;
            $arr['attr'] = $attr;
            $arr['goods_id'] = $goods_id;
            $arr['cart_id'] = 0;
            $ret['list'][] = $arr;
        }



        $balance = MemberModel::where(['id' => $user_id])->value('balance');

        return [
            'code'    => 200,
            'message' => '成功',
            'address' => $address,
            'balance' => $balance,
            'data'    => $ret
        ];
    }


    /*
     * 用户端 - 生成订单
     * @param  string $user_id  会员ID
     */
    public function generating_order()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];
        // 获取参数
      $data = json_decode($this->decrypt(Request::instance()->param('Keys')), true);

      write_log($this->decrypt(Request::instance()->param('Keys')));
      if($data['data']['price']+$data['data']['freight'] <= 0  || $data['data']['price'] <= 0) return ['code' => 400, 'message' => '大哥,你要干啥'];
        // $data = json_decode(Request::instance()->param('Keys'));
        // $user_id = Request::instance()->param('user_id', '21');
//         $data = [
//             'user_id' => '21',
//             'address' => [
//                 'name'      => '小王',
//                 'phone'     => '13945668331',
//                 'area_info' => '黑龙江省 哈尔滨市 南岗区',
//                 'address'   => '黑龙江省哈尔滨市南岗区洪波会馆'
//             ],
//             'data'    => [
//                     'price'            => '79.00',
//                     'pay_price'            => '5.00',
//                     'pay_way'          => '余额支付',
//                     'use_balance'          => '2.00',
//                     'use_integral' => '300',
//                     'freight' => '2.00',
//                     'list'             => [
//                         [
//                             "goods_id"          => '1449',
//                             "attr"              => '黑色,S',
//                             "number"            => '2',
//                             "price"             => '1.00',
//                             'member_id'         => '1',
//                             "title"             => '2',
//                             "thumb_img"         => 'uploads/20180723/thumb_f3d2b33ce8eb28ebbe6ddee6cad6a042.jpg',
//                         ],
//                         [
//                             "goods_id"          => '1448',
//                             "attr"              => '',
//                             "number"            => '1',
//                             "price"             => '1.00',
//                             'member_id'         => '1',
//                             "title"             => '1',
//                             "thumb_img"         => 'uploads/20180720/thumb_15e27e6393fff45b9ac585256b0d1488.png',
//                         ]
//                     ]
//
//             ]
//
//         ];


        //if (empty($data['user_id'])) throw new Exception('not Empty');
//        $data = '{
// "data": {
//  "freight": "0.02",
//  "list": [{
//   "thumb_img": "uploads\/20180619\/thumb_ae20ce4d794941f972ad7f590e6b3011.jpg",
//   "title": "溢彩年华 蓝色 时尚简易衣柜衣橱 布衣柜 DKB2-032",
//   "number": "1",
//   "attr": "",
//   "price": "69.00",
//   "member_id": "711",
//   "goods_id": "558"
//  }, {
//   "thumb_img": "uploads\/20180711\/thumb_07a483ac15268949b5f701725d0fe608.png",
//   "title": "0.01",
//   "number": "2",
//   "attr": "",
//   "price": "0.01",
//   "member_id": "711",
//   "goods_id": "1447"
//  }],
//  "price": "69.02"
// },
// "address": {
//  "area_info": "内蒙古自治区 通辽市 科尔沁区",
//  "address": "122222222",
//  "phone": "18646011203",
//  "name": "1"
// },
// "user_id": "848"
//}';
//        $data = json_decode($data,true);
//        halt($data);
        // 启动事务
        Db::startTrans();
        try {

            //Db::name('member')->where('id',$data['user_id'])->setDec('balance',$data['data']['use_balance']);
            //Db::name('member')->where('id',$data['user_id'])->setDec('integral',$data['data']['use_integral']);
            // 生成总订单号码
            $order_number = $this->createNumber();
            $shop_order_number = $this->make_order($data['user_id']);

            $information = [
                'shop_id'           => 0,
                'member_id'         => $data['user_id'],
                'order_number'      => $order_number,
                'shop_order_number' => $shop_order_number,
                'coupon_id'         => 0,
                'coupon_price'      => 0,
                'red_packet_id'     => 0,
                'red_packet_price'  => 0,
                'freight'           => $data['data']['freight'],
                'price'             => $data['data']['price']+$data['data']['freight'],
                'message'           => '',
                // 'goods'             => serialize($value['list']),
                'address_name'      => $data['address']['name'],
                'address_phone'     => $data['address']['phone'],
                'address_area'      => $data['address']['area_info'],
                'address_site'      => $data['address']['address'],
                'status'            => '0',
                'way'               => '-',
                'use_balance'       => 0,
                'use_integral'      => 0,
                // 'single_way'        => 1,
                'create_time'       => time()
            ];
            // 插入订单主表
            $order_id = Db::name('member_order')->insertGetId($information);
            // 处理
            $attachedData = ''; //批量添加附表
            $o_price = 0;
            foreach ($data['data']['list'] as $k => $val){
                if (!empty($val['attr'])) {
                    $goods_price = Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->value('price');
                    if($goods_price != $val['price']){
                        return ['code' => 401, 'message' => '金额不正确1'];
                    }
                    // 减少属性表库存
                    $inventory_attr = Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->value('inventory');
                    if ($inventory_attr) {
                        if ($inventory_attr < $val['number']) {
                            return ['code' => 401, 'message' => $val['title'] . '(' . $val['attr'] . '),库存不足'];
                        }
                        $residue = $inventory_attr - $val['number'];
                        Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->update(['inventory' => $residue]);
                    }
                }else{
                    $goods_price = Db::name('shop_goods')->where(['id' => $val['goods_id']])->value('price');
                    if($goods_price != $val['price']){
                        write_log($goods_price.'/');
                        write_log($val['price']);
                        return ['code' => 401, 'message' => '金额不正确2'];
                    }
                    $inventory_find = Db::name('shop_goods')->where(['id' => $val['goods_id']])->value('inventory');
                    if ($inventory_find < $val['number']) {
                        return ['code' => 401, 'message' => $val['title'] . ',库存不足'];
                    }
                    Db::name('shop_goods')->where(['id' => $val['goods_id']])->setDec('inventory', $val['number']);
                    // 减少主表库存
                }
                $o_price += $goods_price*$val['number'];



                Db::name('shop_goods')->where(['id' => $val['goods_id']])->setInc('sale_number', $val['number']);

                $attachedData[] = [
                    'order_id'          => $order_id,
                    'order_number'      => $order_number,
                    'shop_order_number' => $shop_order_number,
                    'goods_id'          => $val['goods_id'],
                    'attr'              => $val['attr'],
                    'number'            => $val['number'],
                    'price'             => $val['price'],
                    'title'             => $val['title'],
                    'thumb_img'         => $val['thumb_img'],
                    'rebate_percentage' => 0,
                    'limited_status'    => 0,
                    'status'            => '2'
                ];
                $goods_id[] = $val['goods_id'];
            }
            if($o_price != $data['data']['price']){
                return ['code' => 200, 'message' => '金额不正确3'];
            }


            // 批量插入附表
            Db::name('member_order_attached')->insertAll($attachedData);
            $goods_sum = db('member_order_attached')->where('shop_order_number',$shop_order_number)->sum('number');
            $message_id = db('member_message')->insertGetId(['type' => 2,'member_id' => $data['user_id'],'title' => $shop_order_number,'content' => '您的订单已生成,共'.$goods_sum.'商品','create_time' => date('Y-m-d H:i:s',time())]);
            db('mem_mess')->insert(['member_id' => $data['user_id'],'message_id' => $message_id,'create_time' => time(),'click' => 0]);
            // 清空购物车
            Db::name('member_shopping_cart')->where(['member_id' => $data['user_id'], 'goods_id' => ['in', $goods_id]])->delete();


            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功', 'shop_order_number' => $shop_order_number];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 501, 'message' => $e->getMessage(),'getLine' => $e->getLine()];
        }

    }

    public function generating_order_xiao()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        //$data = json_decode($this->decrypt(Request::instance()->param('Keys')), true);
        $data = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        Log::record('okbu');
        Log::record($data);
        $data = $data['Keys'];
        // $data = json_decode(Request::instance()->param('Keys'));
        // $user_id = Request::instance()->param('user_id', '21');
        // $data = [
        //     'user_id' => '21',
        //     'goods_id' => '21,25,30',
        //     'address' => [
        //         'name'      => '小王',
        //         'phone'     => '13945668331',
        //         'area_info' => '黑龙江省 哈尔滨市 南岗区',
        //         'address'   => '黑龙江省哈尔滨市南岗区洪波会馆'
        //     ],
        //     'shop'    => [
        //         [
        //             'title'            => '阿坤旗舰店',
        //             'shop_id'          => '1',
        //             'coupon_id'        => '2',
        //             'coupon_price'     => '5',
        //             'red_packet_id'    => '2',
        //             'red_packet_price' => '5',
        //             "freight"          => '9',
        //             'price'            => '79.00',
        //             'message'          => '好好弄啊!',
        //             'list'             => [
        //                 [
        //                     "goods_id"          => '13',
        //                     "attr"              => '',
        //                     "number"            => '2',
        //                     "price"             => '10.00',
        //                     'member_id'         => '1',
        //                     "title"             => '测试无属性的',
        //                     "thumb_img"         => 'uploads/20170214/thumb_459b5828c870c2cd334f1f2660aa750f.jpg',
        //                     "rebate_percentage" => '3',
        //                     "limited_status"    => '0',
        //
        //                 ],
        //                 [
        //                     "goods_id"          => '12',
        //                     "attr"              => '红色,XL',
        //                     "number"            => '6',
        //                     "price"             => '8.00',
        //                     'member_id'         => '1',
        //                     "title"             => '时尚女装',
        //                     "thumb_img"         => 'uploads/20170215/thumb_cf9f21d87b1949115f4dc3aaec959996.jpg',
        //                     "rebate_percentage" => '3',
        //                     "limited_status"    => '1'
        //                 ]
        //             ]
        //         ],
        //         [
        //             'title'            => '自营的店铺',
        //             'shop_id'          => '3',
        //             'coupon_id'        => '3',
        //             'coupon_price'     => '6',
        //             'red_packet_id'    => '',
        //             'red_packet_price' => '0',
        //             "freight"          => '4',
        //             'price'            => '98.00',
        //             'message'          => '快点发货啊!',
        //             'list'             => [
        //                 [
        //                     "goods_id"          => '11',
        //                     "attr"              => '黑色,纯皮',
        //                     "number"            => '1',
        //                     "price"             => '100.00',
        //                     'member_id'         => '3',
        //                     "title"             => '帕迪欧男士手包大容量手拿包男长款钱包休闲男包',
        //                     "thumb_img"         => 'uploads/20170214/thumb_459b5828c870c2cd334f1f2660aa750f.jpg',
        //                     "rebate_percentage" => '1',
        //                     "limited_status"    => '0'
        //
        //                 ]
        //             ]
        //         ]
        //     ]
        //
        // ];
        // halt($data);

       // if (empty($data['user_id'])) throw new Exception('not Empty');

        // 启动事务
        Db::startTrans();
        try {

            // 生成总订单号码
            $order_number = $this->createNumber();

            // 处理
            $attachedData = ''; //批量添加附表

            // foreach (json_decode($data['shop'], true) as $key => $value) {
            foreach ($data['shop'] as $key => $value) {

                if ($data['user_id'] == $value['shop_id']) return ['code' => 401, 'message' => '不能购买自己的商品'];

                // 更改优惠券状态
                if (!empty($value['coupon_id'])) {

                    // 优惠券改变状态
                    Db::name('member_coupon')->where(['member_id' => $data['user_id'], 'status' => '2', 'id' => $value['coupon_id']])->update(['status' => '1']);

                }

                // 更改红包状态
                if (!empty($value['red_packet_id'])) {

                    // 红包改变状态
                    Db::name('member_packet')->where(['member_id' => $data['user_id'], 'status' => '2', 'id' => $value['red_packet_id']])->update(['status' => '1']);

                }

                // 店铺订单号
                $shop_order_number = $this->make_order($data['user_id']);

                // 分销生成订单记录
                $this->brokerage($data['user_id'], $value['charges'], $shop_order_number, $value['shop_id']);

                // 主表信息
                $information = [
                    'shop_id'           => $value['shop_id'],
                    'member_id'         => $data['user_id'],
                    'order_number'      => $order_number,
                    'shop_order_number' => $shop_order_number,
                    'coupon_id'         => $value['coupon_id'],
                    'coupon_price'      => $value['coupon_price'],
                    'red_packet_id'     => $value['red_packet_id'],
                    'red_packet_price'  => $value['red_packet_price'],
                    'freight'           => $value['freight'],
                    'price'             => $value['price'],
                    'message'           => $value['message'],
                    // 'goods'             => serialize($value['list']),
                    'address_name'      => $data['address']['name'],
                    'address_phone'     => $data['address']['phone'],
                    'address_area'      => $data['address']['area_info'],
                    'address_site'      => $data['address']['address'],
                    'status'            => '0',
                    'way'               => '未支付',
                    // 'single_way'        => 1,
                    'create_time'       => time()
                ];

                // 插入订单主表
                $order_id = Db::name('member_order')->insertGetId($information);

                // foreach (json_decode($value['list'], true) as $val) {
                foreach ($value['list'] as $val) {

                    if (!empty($val['attr'])) {

                        // 减少属性表库存
                        $inventory_attr = Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->value('inventory');
                        $p = Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->value('price');
                        if($p != $val['price']){
                            return ['code' => 401, 'message' => '滚犊子.'];
                        }
                        if ($inventory_attr) {
                            if ($inventory_attr < $val['number']) {
                                return ['code' => 401, 'message' => $val['title'] . '(' . $val['attr'] . '),库存不足'];
                            }
                            $residue = $inventory_attr - $val['number'];
                            Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->update(['inventory' => $residue]);
                        }
                    }

                    // 减少主表库存
                    $inventory_find = Db::name('shop_goods')->where(['id' => $val['goods_id']])->value('inventory');
                    $p = Db::name('shop_goods')->where(['id' => $val['goods_id']])->value('price');
                    if($p != $val['price']){
                        return ['code' => 401, 'message' => '滚犊子。'];
                    }
                    if ($inventory_find < $val['number']) {
                        return ['code' => 401, 'message' => $val['title'] . ',库存不足'];
                    }

                    Db::name('shop_goods')->where(['id' => $val['goods_id']])->setDec('inventory', $val['number']);
                    Db::name('shop_goods')->where(['id' => $val['goods_id']])->setInc('sale_number', $val['number']);

                    $attachedData[] = [
                        'order_id'          => $order_id,
                        'order_number'      => $order_number,
                        'shop_order_number' => $shop_order_number,
                        'goods_id'          => $val['goods_id'],
                        'attr'              => $val['attr'],
                        'number'            => $val['number'],
                        'price'             => $val['price'],
                        'title'             => $val['title'],
                        'thumb_img'         => $val['thumb_img'],
                        'rebate_percentage' => $val['rebate_percentage'],
                        'limited_status'    => $val['limited_status'],
                        'status'            => '2'
                    ];

                    // 是否是特价
                    if (!empty($val['limited_status'])) {

                        $limited = Db::name('limited')->where(['goods_id' => $val['goods_id']])->field('number,purchase_number')->find();

                        if (!empty($limited)) {

                            if (($limited['purchase_number'] + $val['number']) > $limited['number']) return ['code' => 402, 'message' => '特价商品数量已不足'];

                            Db::name('limited')->where(['goods_id' => $val['goods_id']])->setInc('purchase_number', $val['number']);

                        }

                    }

                }

            }

            // 批量插入附表
            Db::name('member_order_attached')->insertAll($attachedData);

            // 清空购物车
            Db::name('member_shopping_cart')->where(['member_id' => $data['user_id'], 'goods_id' => ['in', $data['goods_id']]])->delete();

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功', 'order_number' => $order_number];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => $e->getMessage()];
        }

    }
    //余额支付
    public function balance_pay_order(){
        $ret = $this->pay_order();
        return $ret;
    }

    public function pay_order(){
        $order_number = Request::instance()->param('shop_order_number');
        $user_id = Request::instance()->param('user_id');
        $use_integral = Request::instance()->param('use_integral');
        $use_balance = Request::instance()->param('use_balance');
        $pay_price = Request::instance()->param('pay_price');
        $pay_way = Request::instance()->param('pay_way');
        if (empty($order_number) || empty($user_id)) throw new Exception('not Empty');
        $balance = Db::name('member')->where('id',$user_id)->value('balance');
        $integral = Db::name('member')->where('id',$user_id)->value('integral');
        if($use_balance > $balance) return ['code' => 400, 'message' => '余额不足'];
        if($use_integral > $integral) return ['code' => 400, 'message' => '积分不足'];
        $order_find =Db::name('member_order')->where(['member_id' => $user_id,'order_number|shop_order_number' => $order_number])->find();
        if($use_integral+$use_balance < $order_find['price']) return ['code' => 400, 'message' => '金额不对'];
        if($order_find['price'] <= 0) return ['code' => 400, 'message' => '滚犊子'];
        if($order_find['status'] !=0){
            return ['code' => 400, 'message' => '订单已不是未支付状态'];
        }
        Db::startTrans();
        try {
            write_log($order_find['shop_order_number']);
            $this->fenxiao($order_find['shop_order_number']);
            $update = [
                'member_id' => $user_id,
                'status' => 1,
                'use_integral' => $use_integral,
                'pay_time' => time(),
                'use_balance' => $use_balance,
                'pay_price' => $pay_price,
                'way' => $pay_way,
            ];
            // 更新未支付状态
            $att = Db::name('member_order')->where(['member_id' => $user_id, 'status' => '0', 'order_number|shop_order_number' => $order_number])
                ->update($update);
            Db::name('member')->where('id',$user_id)->setDec('balance',$use_balance);
            Db::name('member')->where('id',$user_id)->setDec('integral',$use_integral);
            $goods_sum = db('member_order_attached')->where('shop_order_number',$order_number)->sum('number');
            $message_id = db('member_message')->insertGetId(['type' => 2,'member_id' => $user_id,'title' => $order_number,'content' => '您的订单已支付,共'.$goods_sum.'商品','create_time' => date('Y-m-d H:i:s',time())]);
            db('mem_mess')->insert(['member_id' => $user_id,'message_id' => $message_id,'create_time' => time(),'click' => 0]);
            Db::commit();
            return ['code' => 200, 'message' => '成功'];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 500, 'message' => $e->getMessage(),'line' => $e->getLine()];
        }
    }

    public function fen(){
        //return (new Area())->province_list();
        db('test')->insert(['content' => time()]);

    }


    public function test1()
    {
        $limit = 999;
        $time = date('Y-m-d H:i:s',time());
        $list = Db::name('member_order')
            ->where('status','neq',0)
            ->where('create_time', 'between', ['1537027200','1537113600'])

            ->select();

        //8月15-9月17号;
        //halt($list);
        //30 2663
//        dump($list);
//        $list1 = Db::name('member_order')
//            ->where('status','neq',0)
//            ->whereTime('create_time', 'between', ['1537113600',time()])
//            ->select();
//
//        halt($list1);



       foreach ($list as $value){
           $this->fenxiao($value['shop_order_number']);
           dump($value['shop_order_number']);
           dump($limit);
           Db::name('text_order')->insert(['shop_order_number' => $value['shop_order_number'],'limit' => $limit]);
       }
       return $time;

    }
    public function test2(){
        Db::name('member_order')->where('status','neq',0)->whereTime('create_time', 'between', ['1537113600',time()])->chunk(10, function($users) {
            foreach ($users as $user) {
                halt($user);
                $this->fenxiao($user['shop_order_number']);
            }
        });
    }


    protected function fenxiao($shop_order_number){

        write_log('fenxiaojiekou '.date('Y-m-d H:i:s',time()));
        $order_find = Db::name('member_order')->where(['order_number|shop_order_number' => $shop_order_number])->find();
        if($order_find['status'] !=0){
           // return ['code' => 400, 'message' => 'error'];
           // die;
        }

        $member_distribution_data = Db::name('member_distribution_records')->where('shop_order_number',$shop_order_number)->find();
        if(!empty($member_distribution_data)){
            return ['code' => 400, 'message' => 'error'];
            die;
        }
        //$member_order_goods_count  = Db::name('member_order_attached')->where(['order_number|shop_order_number' => $shop_order_number])->sum('number');
        $member_order_goods_count = $order_status1_goods_sum = Db::name('member_order a')
            ->where('a.status','egt',1) //已支付所有商品数量 fanli 1
            ->where('member_id',$order_find['member_id'])
            ->join('member_order_attached b','a.shop_order_number = b.shop_order_number')
            ->sum('number');

        if(is_null($order_status1_goods_sum)) $order_status1_goods_sum = 0;
        $now_order_goods_count = Db::name('member_order a')  //当前订单商品数量 fanli 1
            ->where('a.shop_order_number',$shop_order_number)
            ->join('member_order_attached b','a.shop_order_number = b.shop_order_number')
            ->sum('number');

        $hierarchy = Db::name('member_distribution')->where(['referrals_id' => $order_find['member_id']])->value('hierarchy');
        // 判断是否存在
        if (!empty($hierarchy)) {
            $hierarchy = explode(',', $hierarchy);      // 变成数组
            array_shift($hierarchy);                    // 去掉第一个key
            array_pop($hierarchy);                      // 去掉最后一个key
            $hierarchy = array_slice($hierarchy, -10);   // 倒数3个
            rsort($hierarchy);                       // 逆向排序
        }
        $web_y = db('config')->where('varname','web_y')->value('varvalue');
        $web_e = db('config')->where('varname','web_e')->value('varvalue');
        $web_f = db('config')->where('varname','web_f')->value('varvalue');
        $web_g = db('config')->where('varname','web_g')->value('varvalue');
        $web_gt = db('config')->where('varname','web_gt')->value('varvalue');
//        $y = bcmul($order_find['price'],$web_y/100,2);
//        $e = bcmul($order_find['price'],$web_e/100,2);
//        $f = bcmul($order_find['price'],$web_f/100,2);
//        $g = bcmul($order_find['price'],$web_g/100,2);
//        $gt = bcmul($order_find['price'],$web_gt/100,2);
        $y = bcmul($now_order_goods_count,$web_y,2);
        $e = bcmul($now_order_goods_count,$web_e,2);
        $f = bcmul(1,$web_f,2);
        $g = bcmul($now_order_goods_count,$web_g,2);
        $gt = bcmul($now_order_goods_count,$web_gt,2);
        $time = date('Y-m-d H:i:s',time());
//        $member_order_goods_count = $member_order_goods_count%10;
//        if($member_order_goods_count == 0) $member_order_goods_count = 10;
        $session_get_shop_order_number = Session::get($shop_order_number);
        //if(!empty($session_get_shop_order_number)) return ['code' => 400,'message' => '同一订单不允许重复提交'];
        Session::set($shop_order_number,$shop_order_number);
        Db::startTrans();
        try {
            if (!empty($hierarchy)) {
                foreach ($hierarchy as $k => $v) {
                    if ($k + 1 == 1) { //$k+1代表当前级别
                        Db::name('member')->where('id', $v)->setInc('y', $y);
                        $insert = [
                            'shop_order_number' => $shop_order_number,
                            'member_id' => $v,
                            'type' => 'y',
                            'price' => $y,
                            'create_time' => $time
                        ];
                        Db::name('member_distribution_records')->insert($insert);
                    }
                    if ($k + 1 == 2) {
                        Db::name('member')->where('id', $v)->setInc('e', $e);
                        $insert = [
                            'shop_order_number' => $shop_order_number,
                            'member_id' => $v,
                            'type' => 'e',
                            'price' => $e,
                            'create_time' => $time
                        ];
                        Db::name('member_distribution_records')->insert($insert);
                    }
                    ///

//                    if ($member_order_goods_count == $k + 1) {
//                        Db::name('member')->where('id', $v)->setInc('f', $f);
//                        $insert = [
//                            'shop_order_number' => $shop_order_number,
//                            'member_id' => $v,
//                            'type' => 'f',
//                            'price' => $f,
//                            'create_time' => $time
//                        ];
//                        Db::name('member_distribution_records')->insert($insert);
//                    }

                }
            }

            $order_status1_goods_sum = $order_status1_goods_sum%10;//当数量取余数
            if($order_status1_goods_sum == 0) $order_status1_goods_sum = 10;//如果余数是0就是第10级
            //dump($order_status1_goods_sum);
            $level = [];
            $float = [];
            for ($i = 1; $i <= $now_order_goods_count;$i++){
                $level[] = ($order_status1_goods_sum+$i)%10 ? ($order_status1_goods_sum+$i)%10 : 10;
            }

            //dump($hierarchy);
            //dump($level);
            foreach ($level as $k1 => $v1){
                if(!empty($hierarchy)){
                    foreach ($hierarchy as $k2 => $v2){
                        if($v1 == $k2+1){
                            Db::name('member')->where('id', $v2)->setInc('f',$f);
                            $float[] = [
                                'shop_order_number' => $shop_order_number,
                                'member_id' => $v2,
                                'type' => 'f',
                                'price' => $f,
                                'create_time' => $time
                            ];
                        }
                    }
                }
            }
            if(!empty($hierarchy)) Db::name('member_distribution_records')->insertAll($float);
            //halt($float);


            $member_list = Db::name('member')->where('is_vip', '2')->select();//1是普通会员 2是股东vip

            if ($member_list) {
                $member_insert = [];
                $member_distribution_records_insert = [];
                foreach ($member_list as $k => $v) {
                    $member_insert[] = [
                        'id' => $v['id'],
                        'g' => bcadd($g, $v['g'], 2),
                    ];
                    $member_distribution_records_insert[] = [
                        'shop_order_number' => $shop_order_number,
                        'member_id' => $v['id'],
                        'type' => 'g',
                        'price' => $g,
                        'create_time' => $time
                    ];

                }
                (new MemberModel)->saveAll($member_insert);//股东奖
                (new MemberDistributionRecords())->saveAll($member_distribution_records_insert);//股东记录

            }

            $member_list_gut = Db::name('member')->select();//股东推荐奖
            $member_distribution_records_insert_gt = [];
            foreach ($member_list_gut as $gua => $gub){
                if ($gub['member_id'] != 0) {
                    $arrgt = count(explode(',',$gub['member_id']));
                    $m_gt = Db::name('member')->where('id', $gub['id'])->setInc('gt',$arrgt*$gt);
                    $member_distribution_records_insert_gt[] = [
                        'shop_order_number' => $shop_order_number,
                        'member_id' => $gub['id'],
                        'type' => 'gt',
                        'price' => $arrgt*$gt,
                        'create_time' => $time
                    ];
                }
            }
            if ($member_distribution_records_insert_gt) {
//                    //(new MemberModel)->saveAll($member_insert_gt);//股东推荐奖
                (new MemberDistributionRecords())->saveAll($member_distribution_records_insert_gt);//股东推荐奖记录
            }
//            $member_list_gt = Db::name('member')->where('member_id', 'neq',0)->select();//当前我推荐的推荐会员
//            $member_distribution_records_insert_gt = [];
//            $member_update_gt = [];
//            if($member_list_gt){
//                foreach ($member_list_gt as $kgt => $vgt ){
//                    $arrgt = explode(',',$vgt['member_id']);
//                    if(in_array($order_find['member_id'],$arrgt)){
//                        $member_update_gt[] = [
//                            'id' => $vgt['id'],
//                            'gt' => bcadd($gt,$vgt['gt'], 2)
//                        ];
//                        $member_distribution_records_insert_gt[] = [
//                            'shop_order_number' => $shop_order_number,
//                            'member_id' => $vgt['id'],
//                            'type' => 'gt',
//                            'price' => $gt,
//                            'create_time' => $time
//                        ];
//                    }
//                }
//            }
//
//            if ($member_distribution_records_insert_gt) {
//                    //(new MemberModel)->saveAll($member_insert_gt);//股东推荐奖记录
//                    (new MemberDistributionRecords())->saveAll($member_distribution_records_insert_gt);//股东推荐奖记录
//                }
//            if($member_update_gt){
//                (new MemberModel)->saveAll($member_update_gt);//股东推荐奖
//            }
            $member_total_price = Db::name('member_distribution_records')->where('shop_order_number',$shop_order_number)->field('member_id,sum(price) price')->group('member_id')->select();
            foreach ($member_total_price as $k => $v){
                Db::name('member')->where('id', $v['member_id'])->setInc('balance',bcmul($v['price'],0.9,2));
                Db::name('member')->where('id', $v['member_id'])->setInc('integral',floor(bcmul($v['price'],0.1,2)));
            }
            Db::commit();
            return 'keyi';
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => '500','message' =>$e->getMessage(),'line' => $e->getLine()];
        }



//        foreach ($member_list as $k => $v){
//            Db::name('member')->where('id',$v)->setInc('g',$g);
//            $insert = [
//                'member_id' => $v,
//                'type' => 'g',
//                'price' => $g,
//                'create_time' => $time
//            ];
//            Db::name('member_distribution_records')->insert($insert);
//        }



    }

    public function fenxiao1($shop_order_number){

        $member_order_count  = 0;//会员已下单商品数量
        $dis_member_level_count = 0;//当前分销会员数量
        $dis_member_level = [];//分销级别拼接串一维数组
        $comment_price = 0;//推荐奖价格
        $float_price = 0;//浮动奖价格
        $is_partner = 0;
        $time = time();
        if($dis_member_level_count < 9 && $dis_member_level_count != 0){ //算自己不满10级
            foreach ($dis_member_level as $k => $v){
                if($k+1 == 1){ //$k+1代表当前级别
                    $member_id1 = $comment_price;//1级先给推荐奖
                }
                if($k+1 == 2){
                    $member_id2 = bcdiv($comment_price,2,2);//2级二代推荐奖及1/2
                }
                if($member_order_count == $k+1){ //最多第8单也走这里8级 如果订单数量大于会员级别也不会走到这里来
                    $member_level[$k] = $float_price;//浮动奖
                }

            }
            //上面用来判断下单数量小于分销会员
            if($member_order_count > $dis_member_level_count){
                $member_pingtai[$k] = $float_price;//浮动奖给平台
            }
            //上面用来判断下单数量大于分销会员
        }
        if($dis_member_level_count >= 9){ //大于9级了下单数量小于等于9同上了一样的代码逻辑
            if($member_order_count <= 9){
                foreach ($dis_member_level as $k => $v){//仅仅取出分销会员9级即可取多了会浮动奖有bug
                    if($k+1 == 1){ //$k+1代表级别
                        $member_id1 = $comment_price;//1级先给推荐奖
                    }
                    if($k+1 == 2){
                        $member_id2 = bcdiv($comment_price,2,2);//2几二代先给推荐奖
                    }
                    if($member_order_count == $k+1){
                        $member_level[$k] = $float_price;//浮动奖
                    }

                }
            }else{
                //订单数量大于等于10 100 1000%9余1; 1001%9=2；9%9=0；
                $remainder_member_level = $member_order_count%9;//取余数后的会员级别
                foreach ($dis_member_level as $k => $v){//仅仅取出分销会员9级即可取多了会有bug
                    if($k+1 == 1){ //$k+1代表当前级别
                        $member_id1 = $comment_price;//1级先给推荐奖
                    }
                    if($k+1 == 2){//$k+2代表上一级别
                        $member_id2 = bcdiv($comment_price,2,2);//2几二代先给推荐奖
                    }
                    if($remainder_member_level == $k+1){
                        $member_id1 = $float_price;//浮动奖
                    }

                }
            }
        }
        if($is_partner == 1){
            $is_gudong_shangjia = '股东奖，股东推荐奖';
        }
    }

    public function pay_order_ali_wx(){
        $order_number = Request::instance()->param('shop_order_number');
        $user_id = Request::instance()->param('user_id');

        $order_status =Db::name('member_order')->where(['member_id' => $user_id,'order_number|shop_order_number' => $order_number])->value('status');
        if($order_status !=0){
            return ['code' => 400, 'message' => '订单已不是未支付状态'];
        }
        try {
            Db::startTrans();
            $update = [
                'member_id' => $user_id,
                'status' => 1,
                'pay_time' => time()
            ];
            // 更新未支付状态
            $att = Db::name('member_order')->where(['member_id' => $user_id, 'status' => '0', 'order_number|shop_order_number' => $order_number])
                ->update($update);
            Db::commit();
            return ['code' => 200, 'message' => '成功'];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 500, 'message' => $e->getMessage()];
        }
    }

    public function distribution_records(){
        $member_id = Request::instance()->param('member_id');
        $type = Request::instance()->param('type');
        if($type == 'e') $type = 'y';
        if($type == 'r') $type = 'e';
        $condition = [];
        if(!empty($type)) $condition['a.type'] = ['eq',$type];
        if(!empty($member_id)) $condition['a.member_id'] = ['eq',$member_id];
        $data = (new MemberDistributionRecords())
            ->alias('a')
            ->order('create_time','desc')
            ->where($condition)
            ->join('member_order b','a.shop_order_number = b.shop_order_number')
            ->join('member c','b.member_id = c.id')
            ->field('a.member_id,a.type,a.price,a.create_time,c.avatar,c.username')->paginate(11)->each(function($item,$key){
            switch ($item['type'])
            {
                case 'y':
                    $item['type'] = '一代奖';
                    break;
                case 'e':
                    $item['type'] = '二代奖';
                    break;
                case 'f':
                    $item['type'] = '浮动奖';
                    break;
                case 'g':
                    $item['type'] = '股东奖';
                    break;
                case 'gt':
                    $item['type'] = '股东推荐奖';
                    break;
                default:
                    echo "No number between 1 and 3";
            }
            $item['create_time'] = date('Y-m-d',strtotime($item['create_time']));

        });
        return ['code' => 200, 'message' => '成功','data' => $data];
    }

    public function pay_order1(){
        $order_number = Request::instance()->param('shop_order_number');
        $user_id = Request::instance()->param('user_id');
//        $use_integral = Request::instance()->param('use_integral');
//        $use_balance = Request::instance()->param('use_balance');
//        $pay_price = Request::instance()->param('pay_price');
//        $pay_way = Request::instance()->param('pay_way');
        if (empty($order_number) || empty($user_id) || empty($use_integral) || empty($use_balance) || empty($pay_price) || empty($pay_way)) throw new Exception('not Empty');
        $balance = MemberModel::where(['id' => $user_id])->value('balance');
        if($use_balance > $balance){
            return ['code' => 400, 'message' => '使用金额大于用户金额'];
        }
        $integral = MemberModel::where(['id' => $user_id])->value('integral');
        if($use_integral > $integral){
            return ['code' => 400, 'message' => '使用积分大于用户积分'];
        }
        $order_status =Db::name('member_order')->where(['member_id' => $user_id,'order_number|shop_order_number' => $order_number])->value('status');
        if($order_status !=0){
            return ['code' => 400, 'message' => '订单已不是未支付状态'];
        }
        try {
            Db::startTrans();
            $update = [
                'member_id' => $user_id,
                'use_integral' => $use_integral,
                'use_balance' => $use_balance,
                'pay_price' => $pay_price,
                'way' => $pay_way,
                'status' => 1,
                'pay_time' => time()
            ];
            // 更新未支付状态
            $att = Db::name('member_order')->where(['member_id' => $user_id, 'status' => '0', 'order_number|shop_order_number' => $order_number])
                ->update($update);
            $inventory = Db::name('member_order_attached')->where(['order_number|shop_order_number' => $order_number])->field('goods_id,attr,number,price,shop_order_number')->select();
            // 增加商品销量
            foreach ($inventory as $value) {
                Db::name('shop_goods')->where(['id' => $value['goods_id']])->setInc('sale_number', $value['number']);
            }
            Db::name('member')->where(['id' => $user_id])->setDec('integral', $use_integral);
            Db::name('member')->where(['id' => $user_id])->setDec('balance', $use_balance);
            Db::commit();
            return ['code' => 200, 'message' => '成功'];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 500, 'message' => $e->getMessage()];
        }
    }

    /*
     * 用户端 - 余额支付订单
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     * @param  string $goods_id         商品ID
     */
    public function payment_order()
    {

        // if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $order_number = Request::instance()->param('order_number');
        $user_id = Request::instance()->param('user_id');
        $goods_id = Request::instance()->param('goods_id');

        if (empty($order_number) || empty($user_id)) throw new Exception('not Empty');

        // 查询订单记录
        $order_status = Db::name('member_withdraw')->where(['type_id' => '3', 'status' => '1', 'member_id' => $user_id, 'order_number' => $order_number])
            ->find();

        // 如果为支付
        if (empty($order_status)) {
            // 读取订单金额
            $price = MemberOrderModel::where(['status' => '0', 'member_id' => $user_id, 'order_number|shop_order_number' => $order_number])->sum('price');

            // 我的余额
            $balance = MemberModel::where(['id' => $user_id])->value('balance');

            if ($balance >= $price) {

                // 启动事务
                Db::startTrans();
                try {

                    // 扣余额
                    $result = Db::name('member')->where(['id' => $user_id])->setDec('balance', $price);

                    if ($result) {

                        // 更新状态
                        Db::name('member_order')->where(['member_id' => $user_id, 'status' => '0', 'order_number|shop_order_number' => $order_number])
                            ->update(['status' => '1', 'way' => '余额支付', 'pay_time' => time()]);


                        // 订单属性表
                        $inventory = Db::name('member_order_attached')->where(['order_number|shop_order_number' => $order_number])->field('goods_id,attr,number,price,shop_order_number')->select();

                        // 增加商品销量
                        foreach ($inventory as $value) {
                            Db::name('shop_goods')->where(['id' => $value['goods_id']])->setInc('sale_number', $value['number']);
                        }

                        // 消费记录
                        Db::name('member_withdraw')
                            ->insert(['member_id' => $user_id, 'type_id' => '3', 'balance' => ($balance - $price), 'price' => $price, 'way' => '余额支付', 'status' => '1', 'order_number' => $order_number, 'create_time' => time()]);

                        // 首单增加积分
                        $find = Db::name('integral_record')->where(['member_id' => $user_id, 'type' => '购买'])->value('id');
                        if (empty($find)) {

                            // 送积分
                            Db::name('member')->where(['id' => $user_id])->setInc('integral', Cache::get('web_integral_goods'));

                            // 添加记录
                            Db::name('integral_record')->insert(
                                [
                                    'member_id'   => $user_id,
                                    'type_id'     => '1',
                                    'type'        => '购买',
                                    'integral'    => Cache::get('web_integral_goods'),
                                    'title'       => '（首单）购买商品',
                                    'create_time' => time()
                                ]
                            );

                        }

                        // 购物增加积分
                        $sin = [];
                        $total_integral = 0;
                        foreach ($inventory as $value) {
                            $percentage = Cache::get('web_deduction_percentage');
                            $one_integral = ceil(bcmul($value['price'], $value['number'], 0) * $percentage * 0.01);
                            $sin[] = [
                                'member_id'   => $user_id,
                                'type_id'     => '1',
                                'type'        => '购买',
                                'integral'    => $one_integral,
                                'title'       => $value['shop_order_number'],
                                'create_time' => time()
                            ];
                            $total_integral += $one_integral;

                        }
                        Db::name('integral_record')->insertAll($sin);
                        Db::name('member')->where(['id' => $user_id])->setInc('integral', $total_integral);
                        // 提交事务
                        Db::commit();

                        return ['code' => 200, 'message' => '成功'];
                    }

                } catch (\Exception $e) {

                    // 回滚事务
                    Db::rollback();

                    return ['code' => 401, 'message' => '网络繁忙'];
                }

            }

            return ['code' => 402, 'message' => '余额不足'];
        }

        return ['code' => 402, 'message' => '您已经支付过了,请勿再支付'];

    }

    /*
     * 用户端 - 我的订单
     * @param  string $user_id          会员ID
     */
    public function my_order()
    {

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        // $title = Request::instance()->param('title');
        $status = Request::instance()->param('status', 'all');
        $title = Request::instance()->param('title', '');
        if (empty($user_id)) throw new Exception('not Empty');

        // 搜索条件
        $condition['sun_member_order.member_id'] = ['eq', $user_id];
        $condition['sun_member_order.is_hidden'] = ['eq', 0];

        // 条件
        // if (!empty($title)) $condition['title'] = ['like', '%' . $title . '%'];
        if ($status <> 'all') $condition['sun_member_order.status'] = ['in', $status];
        if ($status == 'all') $condition['sun_member_order.status'] = ['not in', '4,5'];

        $model = new MemberOrderModel();

        $result = $model->where($condition)
            ->field('id,member_id,shop_order_number,price,status,express_number,express_value,freight,is_hidden')
            ->with(['shop' => function ($e) {
                $e->withField('member_id,title');
            },
                'memberOrderAttached'])
            ->order(['sun_member_order.create_time' => 'desc'])
            ->paginate(4);
        if ($title) {
            $result = [];

            //模糊查询店铺名称

            $findShopArr = $model->where($condition)->with(['shop' => function ($query) use ($title) {

                $query->where(['title' => ['like', '%' . $title . '%']]);
            }])->select();
            $findShop = [];
            foreach ($findShopArr as $value) {
                if ($value->shop) {
                    $findShop[] = $value->id;
                }
            }

            //模糊查询附表商品标题

            $findGoods = $model->where($condition)
                ->with(['memberOrderAttached' => function ($e) use ($title) {
                    $e->where(['title' => ['like', '%' . $title . '%']]);
                }])
                ->select();

            $findGoodsId = [];
            foreach ($findGoods as $item) {

                if (count($item['member_order_attached']) > 0) {
                    $findGoodsId[] = $item->id;
                }
            }

            $merge = [];
            if ($findShop && $findGoodsId) {
                foreach ($findShop as &$item) {
                    if (in_array($item, $findGoodsId)) {
                        unset($item);
                    }
                }
                $merge = array_merge($findGoodsId, $findShop);
            } elseif ($findGoodsId && !$findShop) {
                $merge = $findGoodsId;
            } elseif (!$findGoodsId && $findShop) {
                $merge = $findShop;
            }

            $result = $model->where(['id' => ['in', implode(',', $merge)]])
                ->field('id,member_id,shop_id,shop_order_number,price,status,express_number,express_value')
                ->with(['shop' => function ($e) {
                    $e->withField('member_id,title');
                },
                    'memberOrderAttached'])
                ->order(['sun_member_order.create_time' => 'desc'])
                ->paginate(4);


        }
        return [
            'code'    => 200,
            'message' => '成功',
            'data'    => $result
        ];

    }

    public function my_order3(){
        $user_id = Request::instance()->param('user_id');
        // $title = Request::instance()->param('title');
        $status = Request::instance()->param('status', 'all');
        $title = Request::instance()->param('title', '');
        if (empty($user_id)) throw new Exception('not Empty');
        $condition = [];
        // 搜索条件
        $condition['sun_member_order.member_id'] = ['eq', $user_id];

        // 条件
        // if (!empty($title)) $condition['title'] = ['like', '%' . $title . '%'];
        if ($status <> 'all') $condition['sun_member_order.status'] = ['in', $status];
        if ($status == 'all') $condition['sun_member_order.status'] = ['not in', '4,5'];

        $result = Db::name('member_order')
            ->alias('member_order')
            ->where($condition)
            ->field('member_order_attached.*,member_order.status')
            ->join('member_order_attached','member_order.shop_order_number = member_order_attached.shop_order_number')
            ->group('shop_order_number')
            ->where($condition)->paginate(10);
        return [
            'code'    => 200,
            'message' => '成功',
            'data'    => $result
        ];
    }

    /*
     * 用户端 - 取消订单
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     */
    public function cancel_order()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $shop_order_number = Request::instance()->param('shop_order_number');
        // 启动事务
        Db::startTrans();
        try {

            // 改变订单状态
            Db::name('member_order')->where(['shop_order_number' => $shop_order_number])->find();
            $data = Db::name('member_order_attached')->where(['shop_order_number' => $shop_order_number])->select();
            foreach ($data as $k => $val){
                if (!empty($val['attr'])) {
                    Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->setInc('inventory',$val['number']);
                }
                Db::name('shop_goods')->where(['id' => $val['goods_id']])->setDec('inventory', $val['number']);
                Db::name('shop_goods')->where(['id' => $val['goods_id']])->setDec('sale_number', $val['number']);
            }

            $goods_sum = db('member_order_attached')->where('shop_order_number',$shop_order_number)->sum('number');
            $message_id = db('member_message')->insertGetId(['type' => 2,'member_id' => $user_id,'title' => $shop_order_number,'content' => '您的订单已取消,共'.$goods_sum.'商品','create_time' => date('Y-m-d H:i:s',time())]);
            db('mem_mess')->insert(['member_id' => $user_id,'message_id' => $message_id,'create_time' => time(),'click' => 0]);

            Db::name('member_order')->where(['shop_order_number' => $shop_order_number,'status' => 0])->delete();
            Db::name('member_order_attached')->where(['shop_order_number' => $shop_order_number,'status' => 0])->delete();

            Db::commit();

            return ['code' => 200, 'message' => '成功'];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => $e->getMessage()];
        }
    }

    //删除订单
    public function hidden_order(){
        $shop_order_number = Request::instance()->param('shop_order_number');
        $user_id = Request::instance()->param('member_id');
        $ret = Db::name('member_order')->where(['shop_order_number' => $shop_order_number,'member_id' => $user_id])->update(['is_hidden' => 1]);
        if($ret){
            $goods_sum = db('member_order_attached')->where('shop_order_number',$shop_order_number)->sum('number');
            $message_id = db('member_message')->insertGetId(['type' => 2,'member_id' => $user_id,'title' => $shop_order_number,'content' => '您的订单已删除,共'.$goods_sum.'商品','create_time' => date('Y-m-d H:i:s',time())]);
            db('mem_mess')->insert(['member_id' => $user_id,'message_id' => $message_id,'create_time' => time(),'click' => 0]);
            return ['code' => 200, 'message' => '成功'];
        }
        return ['code' => 400, 'message' => '失败'];
    }

    /*
     * 用户端 - 订单确认收货
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     */
    public function order_confirm()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $order_number = Request::instance()->param('shop_order_number');


        // 启动事务
        Db::startTrans();
        try {

            // 更改订单状态
            Db::name('member_order')->where(['shop_order_number' => $order_number, 'member_id' => $user_id])->update(['status' => '3']);

            $goods_sum = db('member_order_attached')->where('shop_order_number',$order_number)->sum('number');
            $message_id = db('member_message')->insertGetId(['type' => 2,'member_id' => $user_id,'title' => $order_number,'content' => '您的订单已收货,共'.$goods_sum.'商品','create_time' => date('Y-m-d H:i:s',time())]);
            db('mem_mess')->insert(['member_id' => $user_id,'message_id' => $message_id,'create_time' => time(),'click' => 0]);

            // 更改金额参数
            //$this->receiving_brokerage($user_id, $order_number);

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功'];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => '网络繁忙'];
        }
    }


    /*
     * 用户端 - 订单退款
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     */
    public function order_refund()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['user_id']) || empty($data['order_number']) || empty($data['type']) || empty($data['amount'])) throw new Exception('not Empty');

        $model = new MemberRefundModel();

        $find = $model->where(['member_id' => $data['user_id'], 'order_number' => $data['order_number']])->value('id');

        if (!empty($find)) return ['code' => 402, 'message' => '该订单已经申请退款,请勿重复申请'];

        $result = $model->allowField(true)->save($data);

        if ($result) {

            // 更改状态
            MemberOrderModel::where(['shop_order_number' => $data['order_number']])->update(['status' => '6']);

            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    /*
     * 用户端 - 订单退款输入运单号
     * @param  string $id               ID
     * @param  string $tracking         物流名称
     * @param  string $tracking_number  物流单号
     */
    // public function order_refund_number()
    // {
    //
    //     if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];
    //
    //     // 获取参数
    //     $data = Request::instance()->param();
    //
    //     if (empty($data['id']) || empty($data['tracking']) || empty($data['tracking_number'])) throw new Exception('not Empty');
    //
    //     $model = new MemberRefundModel();
    //
    //     $find = $model->where(['id' => $data['id'], 'status' => '1'])->value('id');
    //
    //     if (empty($find)) return ['code' => 402, 'message' => '该订单退款暂未通过同意,请耐心等待'];
    //
    //     $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
    //
    //     if ($result) {
    //
    //         return ['code' => 200, 'message' => '成功'];
    //     }
    //
    //     return ['code' => 401, 'message' => '网络繁忙'];
    //
    // }

    public function order_refund_number()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['id']) || empty($data['tracking']) || empty($data['tracking_number'])) throw new Exception('not Empty');

        $model = new MemberRefundModel();

        $find = $model->where(['id' => $data['id'], 'status' => '1'])->value('id');

        if (empty($find)) return ['code' => 402, 'message' => '该订单退款暂未通过同意,请耐心等待'];

        $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

        // 更改订单状态为退货中
        $orderNumber = $model->where('id', $find)->value('order_number');

        Db::name('MemberOrder')->where('order_number', $orderNumber)->update(['status' => 9]);

        if ($result) {

            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }


    /*
     *用户端 - 物流公司
     */
    public function logistics()
    {
        $data = Db::name('express')->where('id', 'in', '2,6,7,8,9,10,11,12,13')->select();

        if ($data) {
            return ['code' => 200, 'data' => $data];
        }
        return ['code' => 401, 'message' => '网络繁忙'];
    }


    /*
     * 用户端 - 订单退款记录
     * @param  string $user_id          会员ID
     */
    public function order_refund_record()
    {

        // 获取参数
        $user_id = Request::instance()->param('user_id');

        if (empty($user_id)) throw new Exception('not Empty');

        // $result = Db::view('member_refund', 'order_number,member_id,type,status,price,create_time')
        //     ->view('member_order', 'id,shop_id,price as goods_price', 'member_order.shop_order_number = member_refund.order_number')
        //     ->view('member_order_attached', 'order_id,goods_id,title,thumb_img,number,price,attr,rebate_percentage', 'member_order_attached.order_id = member_order.id')
        //     ->view('shop', 'member_id as user_id,title as shop_title', 'shop.member_id = member_order.shop_id')
        //     ->where(['member_id' => $user_id])
        //     ->order(['create_time' => 'desc'])
        //     ->select();

        $model = new MemberRefundModel();

        $result = $model->where(['member_id' => $user_id])
            ->field('id,order_number,status,price,create_time,id as shop_title,id as shop_id,id as goods_price')
            ->relation('goodsList,memberOrder')
            ->order(['create_time' => 'desc'])
            ->paginate(4)
            ->toArray();

        return [
            'code'    => 200,
            'message' => '成功',
            'data'    => $result
            // 'data'    => $this->orderGrouping($result, 'shop_title', 'title', 'list', 'member_id', 'shop_id', 'amount', 'amount', 'status', 'status', 'order_number', 'order_number')
        ];

    }

    /*
     * 用户端 - 订单退款记录详情
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     */
    public function order_refund_view()
    {

        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $order_number = Request::instance()->param('order_number');

        if (empty($user_id) || empty($order_number)) throw new Exception('not Empty');

        $result = MemberRefundModel::where(['member_id' => $user_id, 'order_number' => $order_number])
            ->field('id,order_number,type,status,amount,cause,explain,create_time,price,refund_time,tracking,tracking_number,message')
            ->find();

        $memberOrder = MemberOrderModel::where(['shop_order_number' => $order_number])->find();

        $result['number'] = MemberOrderAttachedModel::where(['shop_order_number' => $order_number])->sum('number');

        $result['thumb_img'] = MemberOrderAttachedModel::where(['shop_order_number' => $order_number])->value('thumb_img');

        $shop_id = $memberOrder['shop_id'];

        $result['order_status'] = $memberOrder['status'];


        $result['shop_title'] = ShopModel::where(['member_id' => $shop_id])->value('title');

        return ['code' => 200, 'message' => '成功', 'data' => $result];

    }

    /*
     * 用户端 - 订单详情
     * @param  string $user_id          会员ID
     * @param  string $order_number     店铺订单号
     */
    public function order_view()
    {
        // // 获取参数
        $order_number = Request::instance()->param('shop_order_number');
        $user_id = Request::instance()->param('user_id');

        if (empty($order_number) || empty($user_id)) throw new Exception('not Empty');

        $result = MemberOrderModel::where(['order_number|shop_order_number' => $order_number, 'member_id' => $user_id])
            ->field('pay_price,way,shop_id,shop_order_number,create_time,express_number,express_name,express_value,address_name,address_phone,address_area,address_site,price,status,freight')
            ->find();
        $address = MemberOrderModel::where(['order_number|shop_order_number' => $order_number, 'member_id' => $user_id])
            ->field('address_name,address_phone,address_area,address_site')
            ->find();

        $result['create_time'] = date('Y-m-d H:i:s', $result['create_time']);
        $result['address'] = $address;
        $result['goods_sum_price'] = bcsub($result['price'],$result['freight'],2);

        // 店铺名称
       // $result['shop_title'] = ShopModel::where(['member_id' => $result['shop_id']])->value('title');

        $result['goods'] = MemberOrderAttachedModel::where(['order_number|shop_order_number' => $order_number])
            ->field('goods_id,attr,number,price,title,thumb_img,rebate_percentage')
            ->select();

        return ['code' => 200, 'message' => '成功', 'data' => $result];

    }
//余额支付 混合支付
    public function choose_pay_type(){

        $shop_order_number = Request::instance()->param('shop_order_number');
        $user_id = Request::instance()->param('user_id');
        $integral_money = Db::name('member')->where('id',$user_id)->value('integral');
        $y = Db::name('member')->where('id',$user_id)->value('y');
        $e = Db::name('member')->where('id',$user_id)->value('e');
        $f = Db::name('member')->where('id',$user_id)->value('f');
        $g = Db::name('member')->where('id',$user_id)->value('g');
        $gt = Db::name('member')->where('id',$user_id)->value('gt');
        $arr5 = ['y' => $y,'e' => $e,'f' => $f,'g' => $g,'gt' => $gt];

        //$balance_money = number_format($y+$e+$f+$g+$gt,2,'.','');
        $balance_money = Db::name('member')->where('id',$user_id)->value('balance');
        $order_price =  Db::name('member_order')->where(['order_number|shop_order_number' => $shop_order_number])->value('price');
        //$order_price = Request::instance()->param('price');
        //$order_price = number_format($order_price,2,'.','');
        $balance = Request::instance()->param('balance','0');
        $alipay = Request::instance()->param('alipay','0');
        $wechat = Request::instance()->param('wechat','0');
        $integral = Request::instance()->param('integral','0');
        if(!empty($alipay) && !empty($wechat)){
            $message[] = '支付宝和微信只能选择一种';
            return ['code' => '400','message' => $message ,'pay_price' => 0,'wait_pay_price' =>$order_price,'use_integral' => 0,'use_balance' => 0];
        }
        if(empty($balance) && empty($alipay) && empty($wechat) && empty($integral)){
            $message[] = '请选择至少一种支付方式';
            return ['code' => '400','message' => $message ,'wait_pay_price' =>$order_price ,'pay_price' => 0,'use_integral' => 0,'use_balance' => 0];
        }
        //$message[] = '订单金额为'.$order_price.'元';
        $message1 = [];
        $message_integral = 0;
        $message_pay_way = '';
        if($integral == true){
            //$message[] = '用户积分为'.$integral_money.'积分';
            $min_i = min($order_price,$integral_money);
            //$order_price = bcsub($order_price,$min_i,2);
            if(bcsub($order_price,$min_i,2) == 0){
                $message_pay_way .= '积分-';
                //$message[] = '积分支付为'.number_format($min_i,2,'.','').'积分(使用部分积分)';
                if($order_price == $min_i){
                    $message[] = '积分支付为'.number_format($min_i,2,'.','').'积分(使用全部积分)';
                }else{
                    $message[] = '积分支付为'.number_format($min_i,2,'.','').'积分(使用部分积分)';
                }
                $order_price = bcsub($order_price,$min_i,2);
                return ['code' => '200','message' => $message,'wait_pay_price' =>$order_price ,'pay_price' => 0,'pay_way' => rtrim($message_pay_way,'-'),'use_integral' => $min_i,'use_balance' => 0];
            }else{
                if(empty($alipay) && empty($wechat) && empty($balance)){
                    $message[] = '积分不足,请追加余额、支付宝、微信中一种';
                    $order_price = bcsub($order_price,$min_i,2);
                    return ['code' => '400','message' => $message,'wait_pay_price' =>$order_price,'pay_price' => 0,'pay_way' => '','use_integral' => $min_i,'use_balance' => 0];
                }
                $order_price = bcsub($order_price,$min_i,2);
                $message[] = '积分要支付'.number_format($min_i,2,'.','').'元(使用全部积分)';
                $message_integral = $min_i;
                $message_pay_way .= '积分-';
            }
        }
        $message_balance = 0;
        if($balance == true){
            //$message[] = '用户余额为'.$balance_money.'元';
            $min = min($order_price,$balance_money);
            $message_balance = number_format($min,2,'.','');
            if(bcsub($order_price,$min,2) == 0) {  //余额大于订单金额;
                if($order_price == $balance_money){
                    $message[] = '余额要支付'.$min.'元(使用全部余额)';//全额
                }else{
                    $message[] = '余额要支付'.$min.'元(使用部分余额)';//全额
                }
                $message_pay_way .= '余额-';
                if(empty($alipay) || empty($wechat)){
                    //$message[] = '支付宝或微信选中没有使用';//全额
                }

//                foreach ($arr5 as $k => $v){
//                    $min_b = min($v,$order_price);
//                    if((bcsub($order_price,$min_b)) == 0){
//                        $message1[] = [$k => $order_price];
//                        break;
//                    }
//                    $message1[] = [$k => $v];
//
//                     //dump($order_price_copy).'2';
                $order_price = bcsub($order_price,$min,2);
                return ['code' => '200','message' => $message,'wait_pay_price' =>$order_price,'pay_price' => 0,'pay_way' => rtrim($message_pay_way,'-'),'yefggt' => $message1,'use_integral' => $message_integral,'use_balance' => $message_balance];
            }else{
                if(empty($alipay) && empty($wechat)){
                    $message[] = '余额不足,请追加支付宝、微信中一种';
                    $order_price = bcsub($order_price,$min,2);
                    return ['code' => '400','message' => $message,'wait_pay_price' =>$order_price,'pay_price' => 0,'pay_way' => '','use_integral' => $message_integral,'use_balance' => $message_balance];
                }
                $message[] = '余额要支付'.$min.'元(使用全部余额)';
                $message_pay_way .= '余额-';
//                foreach ($arr5 as $k => $v){
//                    $min_b = min($v,$order_price);
//                    if((bcsub($order_price,$min_b,2)) == 0){
//                        $message1[] = [$k => $order_price];
//                        break;
//                    }
//                    $message1[$k] = $v;
//                    $order_price = bcsub($order_price,$min_b,2);
//                    //dump($order_price_copy).'2';
//                }
                $order_price = bcsub($order_price,$min,2);
            }
        }
        if($alipay == true){
            $message[] = '支付宝要支付'.$order_price.'元';
            $message_pay_way .= '支付宝-';
            return ['code' => '200','message' => $message,'wait_pay_price' =>$order_price,'pay_price' => $order_price,'pay_way' => rtrim($message_pay_way,'-'),'yefggt' => $message1,'use_integral' => $message_integral,'use_balance' => $message_balance];
        }
        if($wechat == true){
            $message[] = '微信要支付'.$order_price.'元';
            $message_pay_way .= '微信-';
            return ['code' => '200','message' => $message,'wait_pay_price' =>$order_price,'pay_price' => $order_price,'pay_way' => rtrim($message_pay_way,'-'),'yefggt' => $message1,'use_integral' => $message_integral,'use_balance' => $message_balance];
        }
        $message[] = '没有选择任何支付方式';
        return ['code' => '400','message' => $message ,'wait_pay_price' =>$order_price,'pay_price' => 0,'pay_way' => ''];
        //1余额 2支付宝 3微信 4积分
    }


    /*
     * 用户端 - 物流详情
     * @param  string $express_number           快递单号
     * @param  string $express_value            快递参数
     */
    public function express_view()
    {
        // // 获取参数
        $express_number = Request::instance()->param('express_number',3831296197200);
        $express_value = Request::instance()->param('express_value','yunda');

        //快递web url https://www.kuaidi100.com/chaxun?com=yunda&nu=3831414533043;
        $url = "https://m.guoguo-app.com/wuliuDetail.htm?mailNo={$express_number}";
        return ['message' => 'url','data' => $url ];
        if (empty($express_value) || empty($express_number)) throw new Exception('not Empty');

        // 快递100
        $data['customer'] = Cache::get('web_express_customer');
        $data['param'] = json_encode(['com' => $express_value, 'num' => $express_number]);
        $data["sign"] = strtoupper(md5($data['param'] . Cache::get('web_express_key') . $data['customer']));

        $information = $this->express_post($data, Cache::get('web_express_url'));

        if (empty($information['com'])) return ['code' => 400, 'message' => '暂无记录'];

        $information['com'] = Db::name('express')->where(['code' => $information['com']])->value('name');

        return $information;

    }

    /*
     * 用户端 - 使用店铺优惠券列表
     * @param  string $user_id 会员ID
     * @param  string $price   金额
     */
    public function coupon_list()
    {
        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $shop_id = Request::instance()->param('shop_id', '0');
        $price = Request::instance()->param('price');

        if (empty($user_id) || empty($price)) throw new Exception('not Empty');

        $model = new MemberCouponModel();

        $result = $model->where(['member_id' => $user_id, 'status' => '2', 'start_time' => ['lt', time()], 'end_time' => ['gt', time()]])
            ->where('virtual_price', 'elt', $price)
            ->where(['shop_id' => [['in', $shop_id], ['eq', '0'], 'OR']])
            ->field('id,title,actual_price,virtual_price,content,start_time,end_time')
            ->order(['create_time' => 'desc'])
            ->paginate(6);

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }

    /*
     * 用户端 - 使用红包列表
     * @param  string $user_id 会员ID
     * @param  string $price   金额
     */
    public function red_packet_list()
    {
        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $price = Request::instance()->param('price');

        if (empty($user_id) || empty($price)) throw new Exception('not Empty');

        $model = new MemberPacketModel();

        $result = $model->where(['member_id' => $user_id, 'status' => '2', 'start_time' => ['lt', time()], 'end_time' => ['gt', time()]])
            ->where('virtual_price', 'elt', $price)
            ->field('id,title,actual_price,virtual_price,content,start_time,end_time')
            ->order(['create_time' => 'desc'])
            ->paginate(6);

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }


    /*
     * 使用3DES加密源数据
     * @param string $oriSource 源数
     * @param string $key 密钥
     * @param string $defaultIV 加解密向量
     * @return string $result   密文
     */
    public function encrypt($oriSource)
    {
        $oriSource = $this->addPKCS7Padding($oriSource);
        $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
        mcrypt_generic_init($td, '123456787418523696385214', '75395182');
        $result = mcrypt_generic($td, $oriSource);
        $result = base64_encode($result);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return $result;
    }


    /*
     * 使用3DES解密密文
     * @param string $encryptedData 密文
     * @param string $key 密钥
     * @param string $defaultIV 加解密向量
     * @return string $result       解密后的原文
     */
    protected function decrypt($encryptedData)
    {

        $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
        mcrypt_generic_init($td, '123456787418523696385214', '75395182');

        $encryptedData = base64_decode($encryptedData);
        $result = mdecrypt_generic($td, $encryptedData);

        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $result = $this->stripPKSC7Padding($result);
        return $result;
    }

    /*
     * 为字符串添加PKCS7 Padding
     * @param string $source 源字符串
     */
    protected function addPKCS7Padding($source)
    {
        $block = mcrypt_get_block_size('tripledes', 'cbc');
        $pad = $block - (strlen($source) % $block);

        if ($pad <= $block) {
            $char = chr($pad);
            $source .= str_repeat($char, $pad);
        }

        return $source;
    }


    /*
     * 去除字符串末尾的PKCS7 Padding
     * @param string $source 带有padding字符的字符串
     */
    protected function stripPKSC7Padding($source)
    {
        $char = substr($source, -1, 1);
        $num = ord($char);
        if ($num > 8) {
            return $source;
        }
        $len = strlen($source);
        for ($i = $len - 1; $i >= $len - $num; $i--) {
            if (ord(substr($source, $i, 1)) != $num) {
                return $source;
            }
        }
        $source = substr($source, 0, -$num);
        return $source;
    }


    /*
     * 订单专用数组分组
     *
     * @param object $data 二维数组
     * @param object $obj 对象
     */
    protected function cartGrouping($data, $val, $title, $list, $val2, $title2, $val3, $title3)
    {
        $result = array_values(array_reduce($data, function ($value, $key) use ($val, $val2, $val3, $title, $title2, $title3, $list) {
            $name = $key[$val];
            $name2 = $key[$val2];
            $name3 = $key[$val3];
            unset($key[$val]);
            $value[$name][$title] = $name;
            $value[$name][$title2] = $name2;
            $value[$name][$title3] = $name3;
            $value[$name][$list][] = $key;
            return $value;
        }));

        return $result;
    }

    /*
     * 订单状态列表专用数组分组
     *
     * @param object $data 二维数组
     * @param object $obj 对象
     */
    protected function orderGrouping($data, $val, $title, $list, $val2, $title2, $val3, $title3, $val4, $title4, $val5, $title5)
    {

        if (empty($data)) return [];

        $result = array_values(array_reduce($data, function ($value, $key) use ($val, $val2, $val3, $val4, $val5, $title, $title2, $title3, $title4, $title5, $list) {
            $name = $key[$val];
            $name2 = $key[$val2];
            $name3 = $key[$val3];
            $name4 = $key[$val4];
            $name5 = $key[$val5];
            unset($key[$val]);
            $value[$name][$title] = $name;
            $value[$name][$title2] = $name2;
            $value[$name][$title3] = $name3;
            $value[$name][$title4] = $name4;
            $value[$name][$title5] = $name5;
            $value[$name][$list][] = $key;
            return $value;
        }));

        return $result;
    }

    /*
     * 生成订单号码
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }

    /*
     * 生成店铺订单号码
     */
    protected function make_order($shop_id)
    {
        return date('YmdHis', time())
        . mt_rand(10, 99)
        . sprintf('%010d', time() - 946656000)
        . sprintf('%03d', (float)microtime() * 1000)
        . sprintf('%03d', (int)$shop_id % 1000);

    }

    /*
     * 快递100 post_curl
     */
    protected function express_post($data, $url)
    {
        $o = "";
        foreach ($data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";        //默认UTF-8编码格式
        }
        // halt($o);
        $post_data = substr($o, 0, -1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //value为0表示直接输出结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $is_success = curl_exec($ch);
        curl_close($ch);
        return json_decode($is_success, true);
    }

    /*
     * 下订单时候佣金分配
     */
    public function brokerage($user_id, $price, $order_number, $shop_id = 0)
    {

        // 分销返利
        $hierarchy = Db::name('member_distribution')
            ->where(['referrals_id' => $user_id])
            ->order(['level' => 'desc'])
            ->value('hierarchy');

        // 判断是否存在
        if (!empty($hierarchy)) {
            $hierarchy = explode(',', $hierarchy);      // 变成数组
            array_shift($hierarchy);                    // 去掉第一个key
            array_pop($hierarchy);                      // 去掉最后一个key
            $hierarchy = array_slice($hierarchy, -3);   // 倒数3个
            rsort($hierarchy);                       // 逆向排序
        }

        // halt($hierarchy);

        // 查看是否开启店铺分销 Y是启用 N是未启用（N默认平台）
        if (Cache::get('web_distribution') == 'Y') {

            $shop = Db::name('shop')->where(['member_id' => $shop_id])->field('one_ratio,two_ratio,three_ratio')->find();

            // 一级分销佣金 给自己返钱
            if (isset($user_id)) {

                // 产生的佣金
                $brokerage = ($price * ($shop['one_ratio'] / 100));

                // 增加佣金 和 总数
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')->insert(['member_id' => $user_id, 'distribution_id' => $user_id, 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // 二级分销佣金
            if (isset($hierarchy[0])) {

                // 产生的佣金
                $brokerage = ($price * ($shop['two_ratio'] / 100));

                // 增加佣金 和 总数
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')
                    ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[0], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // 三级分销佣金
            if (isset($hierarchy[1])) {

                // 产生的佣金
                $brokerage = ($price * ($shop['three_ratio'] / 100));

                // 增加佣金
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')
                    ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[1], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // // 三级分销佣金
            // if (isset($hierarchy[2])) {
            //
            //     // 产生的佣金
            //     $brokerage = ($price * ($shop['three_ratio'] / 100));
            //
            //     // 增加佣金
            //     Db::name('member_brokerage')->where(['member_id' => $hierarchy[2]])->setInc('general_income', $brokerage);
            //     Db::name('member_brokerage')->where(['member_id' => $hierarchy[2]])->setInc('to_yield', $brokerage);
            //
            //     // 添加分销订单
            //     Db::name('member_distribution_order')
            //         ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[2], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            // }

        } else {

            // 一级分销佣金
            if (isset($user_id)) {

                // 产生的佣金
                $brokerage = ($price * (Cache::get('web_one_ratio') / 100));


                // 增加佣金
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')->insert(['member_id' => $user_id, 'distribution_id' => $user_id, 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // 二级分销佣金
            if (isset($hierarchy[0])) {

                // 产生的佣金
                $brokerage = ($price * (Cache::get('web_two_ratio') / 100));

                // 增加佣金
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')
                    ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[0], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // 三级分销佣金
            if (isset($hierarchy[1])) {

                // 产生的佣金
                $brokerage = ($price * (Cache::get('web_three_ratio') / 100));

                // 增加佣金
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('general_income', $brokerage);
                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('to_yield', $brokerage);

                // 添加分销订单
                Db::name('member_distribution_order')
                    ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[1], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            }

            // // 三级分销佣金
            // if (isset($hierarchy[2])) {
            //
            //     // 产生的佣金
            //     $brokerage = ($price * (Cache::get('web_three_ratio') / 100));
            //
            //     // 增加佣金
            //     Db::name('member_brokerage')->where(['member_id' => $hierarchy[2]])->setInc('general_income', $brokerage);
            //     Db::name('member_brokerage')->where(['member_id' => $hierarchy[2]])->setInc('to_yield', $brokerage);
            //
            //     // 添加分销订单
            //     Db::name('member_distribution_order')
            //         ->insert(['member_id' => $user_id, 'distribution_id' => $hierarchy[2], 'brokerage' => $brokerage, 'order_number' => $order_number, 'create_time' => time()]);
            // }

        }
    }

    /*
     * 确认收货时候佣金分配
     */
    protected function receiving_brokerage($user_id, $order_number)
    {

        // 分销返利
        $hierarchy = Db::name('member_distribution')
            ->where(['referrals_id' => $user_id])
            ->order(['level' => 'desc'])
            ->value('hierarchy');

        // 判断是否存在
        if (!empty($hierarchy)) {
            $hierarchy = explode(',', $hierarchy);   // 变成数组
            array_shift($hierarchy);                // 去掉第一个key
            array_pop($hierarchy);                  // 去掉最后一个key
            //            $hierarchy = array_slice($hierarchy, -3);   // 倒数3个
            rsort($hierarchy);                       // 逆向排序
        }

        // 自己分销佣金
        if (isset($user_id)) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $user_id])
                ->value('brokerage');

            // 增加佣金 和 总数
            Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('to_yield', $brokerage);
            Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('actual_amount', $brokerage);
        }

        // 一级分销佣金
        if (isset($hierarchy[0])) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $hierarchy[0]])
                ->value('brokerage');

            // 增加佣金 和 总数
            Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setDec('to_yield', $brokerage);
            Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('actual_amount', $brokerage);

        }

        // 二级分销佣金
        if (isset($hierarchy[1])) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $hierarchy[1]])
                ->value('brokerage');

            // 增加佣金 和 总数
            Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setDec('to_yield', $brokerage);
            Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('actual_amount', $brokerage);
        }

        //判断至少是有3级的
        if (count($hierarchy) >= 3) {
            $hierarchy = array_slice($hierarchy, 2);

            //获取反馈优惠券的信息
            $coupon = Db::name('coupon')->where(['id' => 1])->find();
            if ($coupon) {
                $ini = [];
                foreach ($hierarchy as $key => $item) {
                    $ini[$key]['member_id'] = $item;
                    $ini[$key]['shop_id'] = $coupon['member_id'];
                    $ini[$key]['coupon_id'] = 1;
                    $ini[$key]['title'] = $coupon['title'];
                    $ini[$key]['actual_price'] = $coupon['actual_price'];
                    $ini[$key]['virtual_price'] = $coupon['virtual_price'];
                    $ini[$key]['content'] = $coupon['content'];
                    $ini[$key]['start_time'] = $coupon['start_time'];
                    $ini[$key]['end_time'] = $coupon['end_time'];
                    $ini[$key]['status'] = 2;
                    $ini[$key]['create_time'] = time();
                }
                //批量新增给所有2级后面的会员
                (new MemberCouponModel())->allowField(true)->saveAll(array_values($ini));
            }

        }

    }


    // 未支付订单定时取消（一小时一刷新）
    public function timingCancel()
    {

        // 启动事务
        Db::startTrans();
        try {

            // 查询未支付订单
            $start_time = time() - 3600;
            $end_time = time() - 7200;
            $con = [
                'status'      => 0,
                'create_time' => ['between', [$end_time, $start_time]]
            ];
            $member_orders = Db::name('member_order')->where($con)->field('id,shop_order_number')->select();
            foreach ($member_orders as $value) {

                // 读取特 价商品
                $limited = Db::name('member_order_attached')->where(['shop_order_number' => $value['shop_order_number']])
                    ->field('number,goods_id,attr')->select();

                // 特价商品更改回数量
                if ($limited) {
                    foreach ($limited as $val) {

                        // 增加附表库存
                        if (!empty($val['attr'])) {
                            Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])
                                ->setInc('inventory', $val['number']);
                        }
                        // 增加主表库存
                        Db::name('shop_goods')->where(['id' => $val['goods_id']])->setInc('inventory', $val['number']);

                        Db::name('limited')->where(['goods_id' => $val['goods_id']])->setDec('purchase_number', $val['number']);

                    }
                }

                // 退还积分
                $brokerage = Db::name('member_distribution_order')->where(['order_number' => $value['shop_order_number']])->value('brokerage');

                // 退还分销佣金
                if ($brokerage) {
                    $distribution = Db::name('member_distribution_order')->where('order_number', $value['shop_order_number'])->select();

                    foreach ($distribution as $vs) {

                        Db::name('member_brokerage')->where('member_id', $vs['distribution_id'])->setDec('to_yield', $vs['brokerage']);

                        Db::name('member_brokerage')->where('member_id', $vs['distribution_id'])->setDec('general_income', $vs['brokerage']);

                    }
                }
                // 删除分销订单
                Db::name('member_distribution_order')->where('order_number', $value['shop_order_number'])->delete();


            }

            // 最后改变订单状态
            Db::name('member_order')->where($con)->update(['status' => 5]);

            // 提交事务
            Db::commit();
            // return ['code' => 200, 'message' => '成功'];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();
            // return ['code' => 401, 'message' => '网络繁忙'];
        }
    }

}
